package com.example.learn.http;

import android.app.Application;
import android.widget.Toast;

import com.example.learn.Common;
import com.example.learn.MainActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

public class CommonHttp {

    private String apiUrl;
    private String token;

    public CommonHttp(Application application, String apiUrl, String token) {

        this.apiUrl = apiUrl;
        this.token = token;

        HttpParams httpParams = new HttpParams();
        httpParams.put("token", token);
        OkGo.getInstance().addCommonParams(httpParams).init(application);

    }

    public void post(String url, HttpParams httpParams, CommonCallback commonCallback) {

        OkGo.<String>post(Common.API_URL + url).tag(this).params(httpParams).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                //第三步：处理返回的数据
                String data = response.body();
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String code = jsonObject.getString("code");
                    if (!code.equals("1")) {
                        String msg = jsonObject.getString("msg");
                        commonCallback.onFailure(msg);
                        return;
                    }
                    commonCallback.onSuccess(jsonObject.getString("data"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                commonCallback.onFailure(response.getException().toString());
            }
        });

    }

}
